package com.ikas.ai.server.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@SuppressWarnings("all")
@Component
@Aspect
public class EntityCheckAop {

    /**
     * 定义切入点
     */
    @Pointcut("execution(* com.ikas.pe.server.module.*.controller.*Controller.update*(..))")
    public void checkEntity() {
        // 切入点为所有pageQuery开头的方法
    }

    /**
     * 检查参数是否为空
     */
    @Around("checkEntity()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = ((MethodSignature) pjp.getSignature());
        // 得到拦截的方法
        Method method = signature.getMethod();
        // 获取方法参数注解，返回二维数组是因为某些参数可能存在多个注解
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if (parameterAnnotations == null || parameterAnnotations.length == 0) {
            return pjp.proceed();
        }
        // 获取方法参数名
        String[] paramNames = signature.getParameterNames();
        // 获取参数值
        Object[] paramValues = pjp.getArgs();
        for (Object obj : paramValues) {
            if (!(obj instanceof BindingResult)) {
                continue;
            }
            BindingResult bindingResult = (BindingResult) obj;
            if (bindingResult.hasErrors()) {
                String messages = bindingResult.getAllErrors()
                        .stream()
                        .map(ObjectError::getDefaultMessage)
                        .reduce((m1, m2) -> m2 + "；" + m1)
                        .orElse("参数输入有误！");
                //这里可以抛出自定义异常,或者进行其他操作
                throw new IllegalArgumentException(messages);
            }
        }
        return pjp.proceed(paramValues);
    }
}
